<template>
  <div class="enroll_container">
    <div v-if="!errorStatus">
      <div class="corporation_img">
        <div class="enterprise_logo"><img src="/web-hft-ee/static/img/login/logo_72.png"></div>
        <h3>知业企业大学</h3>

      </div>

      <div class="enroll_form">
        <div class="flex_center type-in-style">
          <input type="text" maxLength="56" placeholder="请输入用户姓名" v-model="username">
        </div>
        <div>
          <van-radio-group v-model="radio" class="flex_start radio_style">
            <van-radio name="2">门店加盟</van-radio>
            <van-radio name="1" :disabled="this.disabledChoose">普通企业</van-radio>
          </van-radio-group>
        </div>


        <div class="flex_center type-in-style">
          <input type="text" placeholder="请输入企业名称" v-model="enterpriseName">
        </div>
        <div class="flex_center type-in-style" v-show="radio==='2'">
          <input type="text" placeholder="请输入企业邀请码" :disabled="unionID" v-model="invitationCode">
        </div>
        <div class="flex_center type-in-style">
          <input maxlength="11" v-model.trim="mobile" placeholder="请填写手机号码"/>
        </div>

        <div class="flex_center type-in-style auto-code-style">
          <input v-model.trim="autoCode" maxlength="6" placeholder="请填写验证码"/>
          <div :class="'autoCodeActive' + (timeNum == 60 ? '' : ' autoCodeActive-grey')" v-html="timeText"
               @click='getAutoCode($event.target)'></div>
        </div>

        <div class="enroll_uploader">
          <van-uploader v-model="fileList" :max-count="1" :after-read="afterRead"
                        :before-read="beforeRead"
                        :max-size="limitSize"
                        @oversize="onOversize"
          >
            <div class="customer-uploading-style">
              <img style="width:80px;height:80px" src="/web-hft-ee/static/img/login/login_upload_pictures.png">
            </div>
            <template #preview-cover="{ file }">
              <div class="preview-cover van-ellipsis">{{ file.name }}</div>
            </template>
          </van-uploader>
        </div>

        <van-progress v-if="percentageType == true" :percentage="percentage" color="#3fb776" class="uploader_progress"/>
        <div class="enroll_uploading_warning flex_start">
          <p><img src="/web-hft-ee/static/img/login/login_hint_icon.png"></p>
          <span>请上传包含您手机号码的名片照片</span>
        </div>

        <div class="flex_center user_service_agreement">
          <van-checkbox v-model="agreed" icon-size="16px">
            <p style="color: #98999E">已阅读并同意<span class="agreement"
                                                  @click="$router.push('/userServiceAgreement')">《用户服务协议》</span></p>
          </van-checkbox>
        </div>

        <div class="confirm" @click="confirm">确认</div>

      </div>
    </div>
    <div v-else>
      <div class="emptyShow">
        <van-empty :description="this.errorInfo"  image="/web-hft-ee/static/img/orgCenter/no_join_enterprise.png" />
      </div>
    </div>
  </div>
</template>

<script>
import {Checkbox, Dialog, Radio, RadioGroup, Toast} from 'vant'

import {pattern} from 'as-common'
import LoginAPI from '../../repo/api/LoginAPI'
import TeamAPI from '../../repo/api/TeamAPI'
import {userActionsTypes} from '../../repo/store/user'
import Exif from 'exif-js'
import RegisterAPI from '../../repo/api/RegisterAPI'

Vue.use(Radio);
  Vue.use(RadioGroup);
  Vue.use(Checkbox);
  Vue.use(Dialog);
  export default {
    name: "enroll",
    data() {
      return {
        username: '',
        userOrg: '',
        mobile: '',
        autoCode: '',
        timeNum: 60,
        submit: false,
        timeText: '获取验证码',
        fileList: [],
        file: '',
        agreed: false,
        radio: '1',
        invitationCode: '',
        enterpriseName: '',
        uploaderImagePath: '',

        percentage: 0,
        percentageType: false,
        unionID: this.$route.query.unionId,
        teamId: this.$route.query.teamId,
        files: {
          name: "",
          type: ""
        },
        headerImage: null,
        picValue: null,
        limitSize: 1024 * 1024 * 5, //MB
        fileStatus: null,
        disabledChoose: false,
        errorStatus: false,
        errorInfo: '',
      }
    },
    mounted() {
      if (this.unionID) {
        //uniodID存在则表示 通过 总部邀请分享出来的链接进行加盟
        RegisterAPI.validRegisteCode(this.unionID).then((result) => {
          if(result.resultCode == '0'){
            this.disabledChoose = true;
            this.radio = '2';
            this.invitationCode = this.unionID;
          }
        }).catch((error) => {
          let result = error.result;
          this.errorStatus = true;
          this.errorInfo =  result[0].resultInfo;
          if (result[0].resultCode === 28) {
            // 28表示自己已经有企业
            let enterpriseInfo = this.$store.getters.enterpriseInfo.enterprise || {};
            if (enterpriseInfo.parentId == this.teamId || enterpriseInfo.id == this.teamId) {
              this.errorInfo = '已经加入该企业或其门店';
              Dialog.confirm({
                title: '提醒',
                message: '您已经在该企业或其门店中',
                confirmButtonText: '前往企业大学'
              }).then(() => {
                this.$_router.replace('/')
              }).catch(() =>{
                console.log('取消');
              })
            } else {
              Dialog.confirm({
                title: '提醒',
                message: '您已加入团队，若需加盟该企业，可前往企业大学退出团队',
                confirmButtonText: '前往企业大学'
              }).then(() => {
                this.$_router.replace('/')
              }).catch(() =>{
                console.log('取消');
              })
            }
          }
        })
      }else{
        //常规注册流程   有企业的话跳首页

        if(this.$store.getters.enterpriseInfo.enterprise){
          this.errorStatus = true;
          this.errorInfo = '请先退出企业';
          Dialog.confirm({
            title: '提醒',
            message: '您已经加入或创建了企业',
            confirmButtonText: '前往企业大学'
          }).then(() => {
            this.$_router.replace('/')
          }).catch(() =>{
            console.log('取消');
          })
        }
      }
    },
    methods: {
      onOversize(file) {
        console.log(file);
        Toast('文件大小不能超过 5MB');
      },
      confirm() {
        let patterns = new RegExp(pattern.mobile);
        if (this.username === '') {
          Toast('请填写用户名');
          return;
        } else if (this.radio === '2' && this.invitationCode === '') {
          Toast('请填写企业邀请码');
          return;
        } else if (this.enterpriseName === '') {
          Toast('请填写企业名称');
          return;
        } else if (this.mobile === '') {
          Toast('请填写手机号码');
          return;
        } else if (!patterns.test(this.mobile)) {
          Toast('请填正确手机号');
          return
        } else if (this.autoCode === '') {
          Toast('请填写验证码');
          return;
        } else if (this.uploaderImagePath === '') {
          Toast('请上传名片照片');
          return;
        } else if (!this.agreed) {
          Toast('同意用户服务协议');
          return;
        }


        let sendData = {
          "username": this.username,
          "type": this.radio,      //1===普通门店  2===门店加盟
          "enterpriseName": this.enterpriseName,
          "registeCode": this.radio === '2' ? this.invitationCode : '',
          "mobile": this.mobile,
          "authCode": this.autoCode,
          "cardPic": this.uploaderImagePath
        };
        //  enterprise.type == 1 总门店  2 == 加盟别人

        TeamAPI.createUniversity(sendData).then((result) => {

          console.log('成功之后的返回。', result);
          this.$store.dispatch(userActionsTypes.FETCH_ENTERPRISE_INFO).then(() => {
            if (result.responseData && result.responseData.enterprise.type === 2) {
              Toast.success('成功加入');
              setTimeout(() => {
                this.$_router.push('/registerResultPage');
              }, 500);

            } else {
              Toast.success('成功注册');
              setTimeout(() => {
                this.$_router.push('/registerResultPage');
              }, 500);
            }

          });
        }).catch(error => {
          Toast(error.result[0].resultInfo);
        })
      },
      beforeRead(file) {
        return true;
      },
      afterRead(file) {
        this.files.name = file.file.name; // 获取文件名
        this.files.type = file.file.type; // 获取类型
        this.picValue = file.file; // 文件流
        this.imgPreview(this.picValue);

        this.percentageType = true;
        this.fileStatus = file

        // let config = {
        //   headers: {
        //     'Content-Type': 'multipart/form-data'
        //   },
        //   onUploadProgress: progressEvent => {
        //     file.status = 'uploading';
        //     file.message = '上传中...';
        //     this.percentage = (progressEvent.loaded / progressEvent.total * 100 | 0);
        //   }
        // }; // 添加请求头
        //
        // const param = new FormData();
        // param.append('file', file.file);
        // // 图片的上传
        // this.$axios.post('https://api.zhiyecn.com/FileUploadServlet?web=h5', param, config).then(res => {
        //   let pic = res.data.responseData.list[0];
        //   this.uploaderImagePath = pic.path;
        //   file.status = 'success';
        //   file.message = '上传成功';
        //   this.percentageType = false
        // }).catch(e => {
        //   console.log('accc---',e);
        //   file.status = 'failed';
        //   file.message = '上传失败';
        //   this.percentageType = false
        // });

      },


      getAutoCode(obj) {
        if (this.timeNum !== 60) return;
        let patt = new RegExp(pattern.mobile);
        let mobile = this.mobile;
        if (mobile == '') {
          Toast('请填写手机号码');
          return
        } else if (!patt.test(mobile)) {
          Toast('请填正确手机号');
          return
        }

        LoginAPI.getAuthCode(this.mobile).then((res) => {
          let resData = res.responseData;
          Toast(resData.msg)
        }).catch((e) => {
          this.clearReciprocal(obj);
          Toast(e.errorInfo)
        })
        this.reciprocal(obj)

      },
      reciprocal(obj) {
        if (this.timeNum === 0) {
          this.clearReciprocal(obj)
          return
        }

        obj.setAttribute('disabled', true);
        this.timeText = '重新获取' + this.timeNum + 's';
        this.timeNum--;
        this.timeIndex = setTimeout(() => {
          this.reciprocal(obj)
        }, 1000)

      },
      clearReciprocal(obj) {
        clearTimeout(this.timeIndex);
        this.timeIndex = null;
        obj.removeAttribute('disabled');
        this.timeText = '获取验证码';
        this.timeNum = 60
      },


      //--------------------------------------------------------------------------------
      // 处理图片
      imgPreview(file) {
        let self = this;
        let Orientation;
        //去获取拍照时的信息，解决拍出来的照片旋转问题
        Exif.getData(file, function () {
          Orientation = Exif.getTag(this, "Orientation");
        });
        // 看支持不支持FileReader
        if (!file || !window.FileReader) return;
        if (/^image/.test(file.type)) {
          // 创建一个reader
          let reader = new FileReader();
          // 将图片2将转成 base64 格式
          reader.readAsDataURL(file);
          // 读取成功后的回调
          reader.onloadend = function () {
            console.log('this.result.length', this.result.length);
            let result = this.result;
            let img = new Image();
            img.src = result;
            //判断图片是否大于5MB,是就直接上传，反之压缩图片
            if (this.result.length <= this.limitSize) {
              self.headerImage = this.result;
              self.postImg();
            } else {
              img.onload = function () {
                let data = self.compress(img, Orientation);
                self.headerImage = data;
                self.postImg();
              };
            }
          };
        }
      },
      // 压缩图片
      compress(img, Orientation) {
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        //瓦片canvas
        let tCanvas = document.createElement("canvas");
        let tctx = tCanvas.getContext("2d");
        // let initSize = img.src.length;
        let width = img.width;
        let height = img.height;
        //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
        let ratio;
        if ((ratio = (width * height) / 4000000) > 1) {
          console.log(`大于400万像素`);
          ratio = Math.sqrt(ratio);
          width /= ratio;
          height /= ratio;
        } else {
          ratio = 1;
        }
        console.log('ratio', ratio);
        canvas.width = width;
        canvas.height = height;
        //        铺底色
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        //如果图片像素大于100万则使用瓦片绘制
        let count;
        if ((count = (width * height) / 1000000) > 1) {
          // console.log("超过100W像素");
          count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
          //            计算每块瓦片的宽和高
          let nw = ~~(width / count);
          let nh = ~~(height / count);
          tCanvas.width = nw;
          tCanvas.height = nh;
          for (let i = 0; i < count; i++) {
            for (let j = 0; j < count; j++) {
              tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
              ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
            }
          }
        } else {
          ctx.drawImage(img, 0, 0, width, height);
        }
        //修复ios上传图片的时候 被旋转的问题
        if (Orientation != "" && Orientation != 1) {
          switch (Orientation) {
            case 6: //需要顺时针（向左）90度旋转
              this.rotateImg(img, "left", canvas);
              break;
            case 8: //需要逆时针（向右）90度旋转
              this.rotateImg(img, "right", canvas);
              break;
            case 3: //需要180度旋转
              this.rotateImg(img, "right", canvas); //转两次
              this.rotateImg(img, "right", canvas);
              break;
          }
        }
        //进行最小压缩
        let ndata = canvas.toDataURL("image/jpeg", 0.1);
        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
        return ndata;
      },
      // 旋转图片
      rotateImg(img, direction, canvas) {
        //最小与最大旋转方向，图片旋转4次后回到原方向
        const min_step = 0;
        const max_step = 3;
        if (img == null) return;
        //img的高度和宽度不能在img元素隐藏后获取，否则会出错
        let height = img.height;
        let width = img.width;
        let step = 2;
        if (step == null) {
          step = min_step;
        }
        if (direction == "right") {
          step++;
          //旋转到原位置，即超过最大值
          step > max_step && (step = min_step);
        } else {
          step--;
          step < min_step && (step = max_step);
        }
        //旋转角度以弧度值为参数
        let degree = (step * 90 * Math.PI) / 180;
        let ctx = canvas.getContext("2d");
        switch (step) {
          case 0:
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0);
            break;
          case 1:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, 0, -height);
            break;
          case 2:
            canvas.width = width;
            canvas.height = height;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, -height);
            break;
          case 3:
            canvas.width = height;
            canvas.height = width;
            ctx.rotate(degree);
            ctx.drawImage(img, -width, 0);
            break;
        }
      },
      //将base64转换为文件
      dataURLtoFile(dataurl) {
        let arr = dataurl.split(",");
        let bstr = atob(arr[1]);
        let n = bstr.length;
        let u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], this.files.name, {
          type: this.files.type
        });
      },
      //这里写接口
      async postImg() {

        // let file = this.dataURLtoFile(this.headerImage);
        // let formData = new window.FormData();
        // formData.append("file", file);
        // // toast_loding(this, "图片上传中···");
        // try {
        //   let res = await util.ajax.post(this.upImgUrl, formData, {
        //     headers: {
        //       "Content-Type": "multipart/form-data"
        //     }
        //   });
        // } catch (e) {
        //   console.log(e);
        // }

        let file = this.dataURLtoFile(this.headerImage);
        let formData = new window.FormData();
        formData.append("file", file);

        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: progressEvent => {
            this.fileStatus.status = 'uploading';
            this.fileStatus.message = '上传中...';
            this.percentage = (progressEvent.loaded / progressEvent.total * 100 | 0);
          }
        }; // 添加请求头

        try {
          await this.$axios.post('https://api.zhiyecn.com/FileUploadServlet?web=h5', formData, config).then(res => {
            let pic = res.data.responseData.list[0];
            this.uploaderImagePath = pic.path;
            this.fileStatus.status = 'success';
            this.fileStatus.message = '上传成功';
            this.percentageType = false
          }).catch(e => {
            this.fileStatus.status = 'failed';
            this.fileStatus.message = '上传失败';
            this.percentageType = false
          });
        } catch (e) {
          console.log(e)
        }
      }

    }
  }
</script>

<style scoped>
  .enterprise_logo {
    width: 72px;
    height: 72px;
    border-radius: 10px;
    overflow: hidden;
    /*box-shadow: 10px 10px 10px #F3F7FE;*/
    box-shadow: 1px 1px 15px rgba(34, 165, 242, .3);
    margin: 40px auto 8px auto;
  }

  .enterprise_logo img {
    width: 100%;
  }

  .corporation_img h3 {
    text-align: center;
  }

  .type-in-style input {
    margin-top: 12px;
    width: 92%;
    border-radius: 25px;
    background-color: #F2F5F8;
    height: 48px;
    text-indent: 12px;

  }

  .corporation_img {
    border-top: 1px transparent solid;
    padding-bottom: 28px;
  }


  .enroll_item > div:nth-of-type(1) {
    text-indent: 20%;
  }

  .enroll_item > div:nth-of-type(1) {
    width: 30%;
  }

  .enroll_item > div:nth-of-type(2) {
    width: 70%;
  }

  .enroll_item input {
    width: 100%;
  }

  .radio_style {
    margin-top: 14px;
    margin-left: 14px;
  }

  .radio_style > div {
    margin-right: 40px;
  }

  .autoCodeActive {
    position: absolute;
    right: 10%;
    top: 42%;
    color: #1DA1F2;

  }

  .autoCodeActive:before {
    content: '|';
    color: #98999E;
    margin-right: 10px;
  }

  .autoCodeActive-grey {
    color: #808080;
  }

  .preview-cover {
    position: absolute;
    bottom: 0;
    box-sizing: border-box;
    width: 100%;
    padding: 4px;
    color: #fff;
    font-size: 12px;
    text-align: center;
    background: rgba(0, 0, 0, 0.3);
  }

  .agreement {
    color: #1DA1F2;
  }

  .accessory_uploading > div:nth-of-type(1) {
    text-indent: 20%;

  }

  .accessory_uploading > div:nth-of-type(1) {
    width: 30%;
    margin-top: 15px;

  }

  .enroll_uploading_warning {
    width: 83%;
    font-size: 12px;
    border-radius: 4px;
    margin: 0px auto 40px auto;
    text-indent: 5px;
    background-color: #E5F5FE;
    color: #1DA1F2;
    height: 32px;
    line-height: 32px;
  }

  .enroll_uploading_warning img {
    width: 16px;
    height: 16px;
    margin-left: 10px;
    margin-top: 30%;
  }

  .confirm {
    width: 80%;
    height: 40px;
    text-align: center;
    line-height: 40px;
    color: white;
    margin: 20px auto;
    border-radius: 25px;
    background-image: linear-gradient(to right, #1DA1F2, #3ECFFA);
  }

  .auto-code-style {
    position: relative;
  }

  .customer-uploading-style {
    width: 88px;
    height: 88px;
    text-align: center;
    font-size: 13px;
    display: table-cell;
    vertical-align: middle;
    background-color: #F2F5F8;
    border-radius: 6px;
    color: #98999E;

  }

  .enroll_uploader {
    margin: 12px auto 12px 24px
  }

  .customer-uploading-style > div:nth-of-type(1) {
    font-weight: bold;
    font-size: 20px;

  }

  .uploader_progress {
    width: 82%;
    margin: 10px auto;
  }
  .emptyShow{
    width: 100%;
    height: 260px;
    position: absolute;
    top: calc(50% - 260px/2);
  }
</style>
